package router

import (
	"fmt"
	"gitee.com/cmoe-login/db"
	"log"
	"net/http"
	"strings"
)

type Chat struct{
	RequestMethod string
	w http.ResponseWriter
	req *http.Request
}

func (chat Chat)IsGet()bool{
	if !chat.IsHandled(){
		return false
	}
	req :=chat.req
	chat.RequestMethod = strings.ToUpper(req.Method)
	if chat.RequestMethod != "GET"{
		log.Println(">> NOT GET METHOD")
		return false
	}
	return true
}

func (chat Chat)IsPost()bool{
	if !chat.IsHandled(){
		log.Println(">> NOT POST METHOD")
		return false
	}
	req :=chat.req
	chat.RequestMethod = strings.ToUpper(req.Method)
	if chat.RequestMethod != "POST"{
		return false
	}
	return true
}

func (chat Chat)IsHandled()bool{
	if chat.req == nil || chat.w == nil{
		log.Println("<< Can't Determine value if the server doesn't even start.")
		return false
	}
	return true
}

func (chat Chat)Log(req *http.Request){
	log.Printf("<< Request Path[%s] Method[%s]\n",req.URL.Path,req.Method)
}

func Serve(addr string,chat *Chat){
	log.Printf("\n>> Cmoe-Chat Server Welcome\n" +
		">> Now Serving At Address\n" +
		">> %s\n",addr)

	server := &http.Server{
		Addr:              addr,
		Handler:           chat,
	}
	if err := server.ListenAndServe();err!=nil{
		log.Println("<< Failed to serve chat server:",err)
		return
	}

}
func (chat Chat)NewUser(req *http.Request)*db.UserLogin{
	return &db.UserLogin{
		Username: req.URL.Query().Get("username"),
		PassWd:   req.URL.Query().Get("passwd"),
	}
}
func (chat Chat)ServeHTTP(w http.ResponseWriter,req *http.Request){
	chat.Log(req)
	chat.w = w;chat.req = req
	reqPath := req.URL.Path // Request Path Definition

	// Hello Handler
	if reqPath == "/hello"{
		if !chat.IsGet(){return}
		fmt.Fprintln(w,"hello this is cmoe-chat")
	}

	// Test Handler
	if reqPath == "/test"{
		if !chat.IsGet(){return}
		fmt.Fprintln(w,"A multi-route test.")
	}

	// Login Handler
	if reqPath == "/user/login"{
		if !chat.IsGet(){return}
		login := chat.NewUser(req)
		login.Login(w,req)
	}

	// Logout Handler
	if reqPath == "/user/logout"{
		if !chat.IsGet(){return}
		login := &db.UserLogin{
			Username: req.URL.Query().Get("username"),
			PassWd:   req.URL.Query().Get("passwd"),
		}
		login.Logout(w,req)

	}

	// Register Handler
	if reqPath == "/user/register"{
		if !chat.IsPost(){return}
		register := &db.UserRegister{
			Username:  "",
			Passwd:    "",
			Nickname:  "",
			Sex:       0,
			Lastip:    "",
			Registime: "",
		}
		register.Register(w,req)
	}

	// Session Verify Handler
	if reqPath == "/user/session/verify"{
		if !chat.IsGet(){return}
		login := &db.UserLogin{}
		login.VerifySession(w,req)
	}

}